import { Button, Icon, Input } from "@rneui/themed";
import { useEffect, useState } from "react";
import { Alert, StatusBar, StyleSheet, View } from "react-native";
import $ajax from "../../utils/Axios/Axios";
import { setAuthToken } from "../../utils/Redux/Actions";
import redux from "../../utils/Redux/Redux";
import storage from "../../utils/Store/Store";

const LOADING_DURATION = 350;

export default function Sign() {
    const [showRegister, setShowRegister] = useState(false)
    return (
        <>
            <StatusBar barStyle="auto" />
            <View style={styles.container}>
                {
                    showRegister
                        ? <Register showLogin={() => { setShowRegister(false) }} />
                        : <Login showRegister={() => { setShowRegister(true) }} />
                }
            </View>
        </>
    )
}

function Login(props) {
    const [userId, setUserId] = useState(undefined)
    const [userIdError, setUserIdError] = useState(undefined)
    useEffect(() => {
        if (userId !== undefined && userId.length === 0) {
            setUserIdError('请输入用户名或注册邮箱')
        } else {
            setUserIdError(undefined)
        }
    }, [userId])

    const [userPassword, setUserPassword] = useState(undefined)
    const [userPasswordError, setUserPasswordError] = useState(undefined)
    useEffect(() => {
        if (userPassword !== undefined && userPassword.length === 0) {
            setUserPasswordError('请输入密码')
        } else {
            setUserPasswordError(undefined)
        }
    }, [userPassword])

    useEffect(() => {
        storage.load('loginInputValue').then((res) => {
            const { userId, userPassword } = res
            setUserId(userId)
            setUserPassword(userPassword)
        })
    }, [])

    const [isLogging, setIsLogging] = useState(false)
    const [loginTitle, setLoginTitle] = useState('登录')
    useEffect(() => {
        if (isLogging) setLoginTitle('登录中')
        else setLoginTitle('登录')
    }, [isLogging])
    useEffect(() => {
        if (isLogging) {
            let nextTitle
            switch (loginTitle) {
                case '登录中...': case '登录':
                    nextTitle = '登录中'
                    break;
                default:
                    nextTitle = `${loginTitle}.`
                    break;
            }
            const timeout = setTimeout(() => {
                setLoginTitle(nextTitle)
            }, LOADING_DURATION)
            return () => {
                if (timeout) {
                    clearTimeout(timeout)
                }
            }
        }
    }, [loginTitle])
    const login = function () {
        setIsLogging(true)
        const validateUserId = userId && userId.length > 0
        const validateUserpassword = userPassword && userPassword.length > 0
        if (!validateUserId) {
            setUserIdError('请输入用户名或注册邮箱')
        }
        if (!validateUserpassword) {
            setUserPasswordError('请输入密码')
        }
        if (!validateUserId || !validateUserpassword) return;

        $ajax.post('/login_and_register/login', { text: userId, password: userPassword })
            .then((res) => {
                console.log({ text: userId, password: userPassword })
                if (res.code === 200) {
                    storage.save('loginInputValue', { userId, userPassword })
                    redux.dispatch(setAuthToken(res.data.token))
                } else {
                    Alert.alert(
                        '登录失败',
                        res.message,
                    )
                }
            }).finally(() => {
                setIsLogging(false)
            })

    }

    const [showPassword, setShowPassword] = useState(false)

    return (
        <>
            <Input
                placeholder="请输入用户名"
                leftIcon={
                    <Icon
                        name="user"
                        type="feather"
                    />
                }
                rightIcon={
                    <Icon
                        name={'x'}
                        type='feather'
                        onPress={() => {
                            setUserId('')
                        }}
                    />
                }
                defaultValue={userId}
                onChangeText={setUserId}
                errorMessage={userIdError}
                renderErrorMessage={userIdError}
            />
            <Input
                placeholder="请输入密码"
                secureTextEntry={!showPassword}
                leftIcon={
                    <Icon
                        name="key"
                        type="feather"
                    />
                }
                rightIcon={
                    <Icon
                        name={showPassword ? 'eye' : 'eye-off'}
                        type='feather'
                        onPress={() => {
                            setShowPassword(!showPassword)
                        }}
                    />
                }
                defaultValue={userPassword}
                onChangeText={setUserPassword}
                errorMessage={userPasswordError}
                renderErrorMessage={userPasswordError}
            />
            <View style={styles.buttonViews}>
                <Button
                    titleStyle={{ width: '90%' }}
                    title={loginTitle}
                    type='solid'
                    onPress={login}
                    disabled={isLogging}
                    disabledStyle={{
                        backgroundColor: '#2089dc'
                    }}
                    disabledTitleStyle={{
                        color: '#d0d0d0'
                    }}
                />
            </View>
            <View style={styles.buttonViews}>
                <Button titleStyle={{ width: '90%' }} title='注册' type='outline' onPress={props.showRegister} />
            </View>
        </>
    )
}

function Register(props) {
    const [showPassword, setShowPassword] = useState(false)
    const [showPasswordForCheck, setShowPasswordForCheck] = useState(false)

    const [username, setUsername] = useState(undefined)
    const [userPassword, setUserPassword] = useState(undefined)
    const [userPasswordForCheck, setUserPasswordForCheck] = useState(undefined)
    const [userEmail, setUserEmail] = useState(undefined)
    const [captcha, setCaptcha] = useState(undefined)

    const [isRegistering, setIsRegistering] = useState(undefined)
    const [registerTitle, setRegisterTitle] = useState('注册')
    useEffect(() => {
        if (isRegistering) setRegisterTitle('注册中')
        else setRegisterTitle('注册')
    }, [isRegistering])
    useEffect(() => {
        if (isRegistering) {
            let nextTitle
            switch (registerTitle) {
                case '注册中...': case '注册':
                    nextTitle = '注册中'
                    break;
                default:
                    nextTitle = `${registerTitle}.`
                    break;
            }
            const timeout = setTimeout(() => {
                setRegisterTitle(nextTitle)
            }, LOADING_DURATION)
            return () => {
                if (timeout) {
                    clearTimeout(timeout)
                }
            }
        }
    }, [registerTitle])
    const register = function () {
        setIsRegistering(true)
    }

    return (
        <>
            <Input
                placeholder="请输入用户名"
                leftIcon={
                    <Icon
                        name="user"
                        type="feather"
                    />
                }
                rightIcon={
                    <Icon
                        name={'x'}
                        type='feather'
                        onPress={() => {
                            setUserId(undefined)
                        }}
                    />
                }
                defaultValue={username}
                onChangeText={setUsername}
                errorMessage="请输入用户名或注册邮箱"
            />
            <Input
                placeholder="请输入邮箱"
                leftIcon={
                    <Icon
                        name="mail"
                        type="feather"
                    />
                }
                rightIcon={
                    <Icon
                        name={'x'}
                        type='feather'
                        onPress={() => {
                            setUserEmail(undefined)
                        }}
                    />
                }
                defaultValue={userEmail}
                onChangeText={setUserEmail}
            />
            <Input
                placeholder="请输入密码"
                secureTextEntry={!showPassword}
                leftIcon={
                    <Icon
                        name="key"
                        type="feather"
                    />
                }
                rightIcon={
                    <Icon
                        name={showPassword ? 'eye' : 'eye-off'}
                        type='feather'
                        onPress={() => {
                            setShowPassword(!showPassword)
                        }}
                    />
                }
                defaultValue={userPassword}
                onChangeText={setUserPassword}
            />

            <Input
                placeholder="请再次输入密码"
                secureTextEntry={!showPasswordForCheck}
                leftIcon={
                    <Icon
                        name="key"
                        type="feather"
                    />
                }
                rightIcon={
                    <Icon
                        name={showPasswordForCheck ? 'eye' : 'eye-off'}
                        type='feather'
                        onPress={() => {
                            setShowPasswordForCheck(!showPasswordForCheck)
                        }}
                    />
                }
                defaultValue={userPasswordForCheck}
                onChangeText={setUserPasswordForCheck}
            />
            <View style={styles.buttonViews}>
                <Button
                    titleStyle={{ width: '90%' }}
                    title={registerTitle}
                    type='solid'
                    onPress={register}
                    disabled={isRegistering}
                    disabledStyle={{
                        backgroundColor: '#2089dc'
                    }}
                    disabledTitleStyle={{
                        color: '#d0d0d0'
                    }}
                />
            </View>
            <View style={styles.buttonViews}>
                <Button titleStyle={{ width: '90%' }} title='返回登录' type='outline' onPress={props.showLogin} />
            </View>
        </>
    )
}

const styles = StyleSheet.create({
    container: {
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100%'
    },
    buttonViews: {
        margin: 5
    }
})